package cn.chenxinjie.hrm.config;

import cn.chenxinjie.hrm.authenhandle.MyAuthenFail;
import cn.chenxinjie.hrm.authenhandle.MyAuthenSuccess;
import cn.chenxinjie.hrm.filter.SmsCodeAuthenticationFilter;
import cn.chenxinjie.hrm.filter.SmsCodeAuthenticationProvider;
import cn.chenxinjie.hrm.filter.SmsCodeFilter;
import cn.chenxinjie.hrm.userdetail.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityBuilder;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author 陈鑫杰
 * @date 2022/3/21 17:30
 */
@Configuration
@EnableWebSecurity
public class SmsCodeConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    private MyUserDetailsService myUserDetailsService ;

    @Autowired
    private MyAuthenSuccess myAuthenSuccess;

    @Autowired
    private MyAuthenFail myAuthenFail;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        //短信验证码登录=========================================================================================
        //短信认证Filter
        SmsCodeAuthenticationFilter smsCodeAuthenticationFilter = new SmsCodeAuthenticationFilter();
        smsCodeAuthenticationFilter.setAuthenticationSuccessHandler(myAuthenSuccess);
        smsCodeAuthenticationFilter.setAuthenticationFailureHandler(myAuthenFail);

        smsCodeAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));

        //短信认证provider
        SmsCodeAuthenticationProvider smsCodeAuthenticationProvider = new SmsCodeAuthenticationProvider();
        smsCodeAuthenticationProvider.setUserDetailsService(myUserDetailsService);


        //添加短信认证provider
        http.authenticationProvider(smsCodeAuthenticationProvider);
        //添加短信认证filter 设置在UsernamePasswordAuthenticationFilter之前
        http.addFilterAfter(smsCodeAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        //短信验证码登录=========================================================================================
    }
}
